package com.roshan.web.util.tile;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.tiles.AttributeContext;
import org.apache.tiles.context.TilesRequestContext;
import org.apache.tiles.locale.impl.DefaultLocaleResolver;
import org.apache.tiles.preparer.ViewPreparer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;

import com.roshan.web.util.constants.CommonConstants;

@Component
@SuppressWarnings("nls")
public class TitleViewPreparer implements ViewPreparer {

    private static final String TITLE_ATTRIBUTE_NAME = "title";

    @Autowired
    private MessageSource messageSource;

    @Override
    public void execute(TilesRequestContext tilesContext, AttributeContext attributeContext) {
        Locale locale = new DefaultLocaleResolver().resolveLocale(tilesContext);

        List<String> attributesList = new ArrayList<String>();
        attributesList.add(TITLE_ATTRIBUTE_NAME);

        for (String attribute : attributesList) {

            if (attributeContext.getAttribute(attribute) != null
                    && attributeContext.getAttribute(attribute).getValue() != null
                    && attributeContext.getAttribute(attribute).getValue().toString().startsWith(
                            CommonConstants.TILE_PREFIX_MESSAGE)) {
                String value = this.messageSource.getMessage(attributeContext.getAttribute(attribute).getValue()
                        .toString(), null, locale);
                attributeContext.getAttribute(attribute).setValue(value);
            }

        }

    }

}
